<?php

namespace App\Models;

class User extends BaseModel
{
    protected static string $table = 'users';

    public static function findByUsername(string $username): ?array
    {
        $db = self::getDb();
        return $db->queryOne(
            "SELECT * FROM `users` WHERE `username` = ?",
            [$username]
        );
    }

    public static function getUserPermissions(int $userId): array
    {
        $db = self::getDb();
        
        $permissions = $db->query(
            "SELECT permission_code FROM user_permissions WHERE user_id = ?",
            [$userId]
        );
        
        return array_column($permissions, 'permission_code');
    }

    public static function createWithPermissions(array $userData, array $permissions): int
    {
        $db = self::getDb();
        
        try {
            $db->beginTransaction();
            
            // 密码加密
            if (isset($userData['password'])) {
                $userData['password'] = password_hash($userData['password'], PASSWORD_DEFAULT);
            }
            
            // 创建用户
            $userId = $db->insert('users', $userData);
            
            // 添加权限
            foreach ($permissions as $permission) {
                $db->insert('user_permissions', [
                    'user_id' => $userId,
                    'permission_code' => $permission
                ]);
            }
            
            $db->commit();
            return $userId;
        } catch (\Exception $e) {
            $db->rollback();
            throw $e;
        }
    }

    public static function updatePermissions(int $userId, array $permissions): bool
    {
        $db = self::getDb();
        
        try {
            $db->beginTransaction();
            
            // 删除旧权限
            $db->delete('user_permissions', 'user_id = ?', [$userId]);
            
            // 添加新权限
            foreach ($permissions as $permission) {
                $db->insert('user_permissions', [
                    'user_id' => $userId,
                    'permission_code' => $permission
                ]);
            }
            
            $db->commit();
            return true;
        } catch (\Exception $e) {
            $db->rollback();
            throw $e;
        }
    }

    public static function verifyPassword(string $password, string $hash): bool
    {
        return password_verify($password, $hash);
    }
}

